package com.minyon_web_admin.common.page;

import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 




import com.minyon_web_admin.common.bean.AjaxResponseBean;

import java.util.Enumeration;

public class MySpringMvcHandlerInterceptor extends HandlerInterceptorAdapter {

	@Override
	/**
	 * This implementation always returns {@code true}.
	 */
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
	 if ( handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Map<String, Object> reqMap = new HashMap<String, Object>();
			MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
		    for(MethodParameter methodParameter : methodParameters){
		    	reqMap.put(methodParameter.getParameterName(),"sss");
		    }
			PageParam rp = handlerMethod.getMethodAnnotation(PageParam.class);
			if (rp == null) {
				 return true;
			}
			Object obj = null;
			
			Enumeration<String> paramNames = request.getParameterNames();
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				// 形成键值对应的map
				reqMap.put(paramName, paramValue);
			}
			reqMap.put("SHOWCOUNT", rp.pageSize());
			PageUtil<Object> page = new PageUtil<Object>();
			page.setSize(rp.pageSize());
			reqMap.put("page", page);
			Method method = handlerMethod.getMethod();
			obj = method.invoke(handlerMethod.getBean(), reqMap);
			 AjaxResponseBean ajaxResult = new AjaxResponseBean();
			if (obj instanceof Map) {
				/*Map<String, Object> resMap = (Map<String, Object>) obj;
				Map<String, Object> resMap2 = new HashMap<String, Object>();
				page.setResult((List<Object>) resMap.get("RESULT"));
				resMap2.put("RESULT", page);*/
				
			}else if(obj instanceof AjaxResponseBean){
				ajaxResult=(AjaxResponseBean) obj;
			}
			JSONObject json = JSONObject.fromObject(ajaxResult);
			response.setHeader("Content-type",
					"application/json;charset=UTF-8");
			PrintWriter writer = response.getWriter();
			writer.print(json.toString());
			writer.close();

			return false;
		} 
		return true;
	}
}
